package com.service.config.annotation.support;

import com.service.config.annotation.LoginUser;
import com.service.config.utils.RedisUtil;
import com.service.config.utils.StringUtils;
import com.service.config.utils.UserTokenManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

/**
 * @author
 * @version 1.0
 * @date 2021/2/5 11:00
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    public static final String LOGIN_TOKEN_KEY = "cloud-Auth-Token";
    @Resource
    private RedisUtil redisUtil;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(String.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {

        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            return null;
        }
        String userId = UserTokenManager.getUserId(token);
        if (StringUtils.isNotEmpty(userId) && redisUtil.exist(token + userId)){
            return userId;
        }
        return null;
    }
}
